package com.imooc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.enums.CommentLevel;
import com.imooc.enums.ErrorMsg;
import com.imooc.exception.CustomException;
import com.imooc.mapper.*;
import com.imooc.pojo.*;
import com.imooc.pojo.vo.*;
import com.imooc.service.ItemService;
import com.imooc.utils.DesensitizationUtil;
import com.imooc.utils.PagedGridResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: 逸尘风清
 * @Date: 2021/5/7
 * @Time: 22:16
 * 描述：
 */

@Service
@Slf4j
public class ItemServiceImpl implements ItemService {
    @Resource
    private ItemsMapper itemsMapper;

    @Resource
    private ItemsParamMapper itemsParamMapper;

    @Resource
    private ItemsSpecMapper itemsSpecMapper;

    @Resource
    private ItemsImgMapper itemsImgMapper;

    @Resource
    private ItemsCommentsMapper itemsCommentsMapper;

    @Resource
    private ItemsCommentsMapperCustom itemsCommentsMapperCustom;

    @Resource
    private ItemsMapperCustom itemsMapperCustom;


    @Override
    public Items queryItemById(String itemId) {
        return itemsMapper.selectByPrimaryKey(itemId);
    }

    @Override
    public List<ItemsImg> queryItemImgList(String itemId) {
        Example example = new Example(ItemsImg.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        List<ItemsImg> itemsImgsList = itemsImgMapper.selectByExample(example);
        return itemsImgsList;
    }

    @Override
    public List<ItemsSpec> queryItemsSpecList(String itemId) {
        Example example = new Example(ItemsSpec.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        List<ItemsSpec> itemsSpecList = itemsSpecMapper.selectByExample(example);
        return itemsSpecList;
    }

    @Override
    public ItemsParam queryItemsParam(String itemId) {
        Example example = new Example(ItemsParam.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        ItemsParam itemsParam = itemsParamMapper.selectOneByExample(example);
        return itemsParam;
    }

    @Override
    public CommentLevelCountsVO queryCommentCounts(String itemId) {
        Integer goodCounts = getCommentsCounts(itemId, CommentLevel.GOOD.type);
        Integer normalCounts = getCommentsCounts(itemId, CommentLevel.NORMAL.type);
        Integer badCounts = getCommentsCounts(itemId, CommentLevel.BAD.type);
        Integer totalCounts = goodCounts+normalCounts+badCounts;
        log.info("查询商品：{}下的评论一共有{}条，其中有{}条好评，{}条中评，{}条差评",itemId,totalCounts,goodCounts,normalCounts,badCounts);
        return new CommentLevelCountsVO(totalCounts,goodCounts,normalCounts,badCounts);
    }

    private Integer getCommentsCounts(String itemId, Integer level){
        ItemsComments condition = new ItemsComments();
        condition.setItemId(itemId);
        if(level != null){
            condition.setCommentLevel(level);
        }
        return itemsCommentsMapper.selectCount(condition);
    }

    @Override
    public PagedGridResult queryPagedComments(String itemId, Integer level, Integer page, Integer pageSize){
        Map<String, Object> map = new HashMap<>();
        map.put("itemId", itemId);
        map.put("commentLevel", level);

        PageHelper.startPage(page, pageSize);
        List<ItemsCommentsVo> itemsCommentsList = itemsCommentsMapperCustom.itemsCommentsList(map);

        for(ItemsCommentsVo vo:itemsCommentsList){
            vo.setNickname(DesensitizationUtil.commonDisplay(vo.getNickname()));
        }

        PagedGridResult pagedGridResult = setterPagedGrid(itemsCommentsList, page);
        return pagedGridResult;
    }

    private PagedGridResult setterPagedGrid(List<?> list,Integer page){
        //包含佷多的分页的数据，需要反馈给前端
        PageInfo<?> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        //当前页
        grid.setPage(page);
        //总记录数
        grid.setRecords(pageList.getTotal());
        //每行显示的内容
        grid.setRows(pageList.getList());
        //总页数
        grid.setTotal(pageList.getPages());
        return grid;
    }

    @Override
    public PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize){
        Map<String, Object> map = new HashMap<>();
        map.put("keywords", keywords);
        map.put("sort", sort);

        PageHelper.startPage(page, pageSize);
        List<SearchItemsVO> searchItemsList = itemsMapperCustom.searchItems(map);

        PagedGridResult pagedGridResult = setterPagedGrid(searchItemsList, page);
        return pagedGridResult;
    }

    @Override
    public PagedGridResult searchItemsByThirdCat(Integer catId, String sort, Integer page, Integer pageSize){
        Map<String, Object> map = new HashMap<>();
        map.put("catId", catId);
        map.put("sort", sort);

        PageHelper.startPage(page, pageSize);
        List<SearchItemsVO> searchItemsList = itemsMapperCustom.searchItemsByThirdCat(map);

        PagedGridResult pagedGridResult = setterPagedGrid(searchItemsList, page);
        return pagedGridResult;
    }

    @Override
    public List<ShopcartVO> queryItemsBySpecIds(String itemSpecIds){
        String[] ids = itemSpecIds.split(",");
        List<String> specIdsList = new ArrayList<>();
        // 将数组中的数据添加到List中
        Collections.addAll(specIdsList,ids);
        return itemsMapperCustom.queryItemsBySpecIds(specIdsList);
    }

    @Override
    public ItemsSpec quertyItemSepcById(String itemSpecId){
        return itemsSpecMapper.selectByPrimaryKey(itemSpecId);
    }

    @Override
    public String queryItemMainImgUrlById(String itemId){
        Example example = new Example(ItemsImg.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemId", itemId);
        criteria.andEqualTo("isMain", 1);
        ItemsImg itemsImg = itemsImgMapper.selectOneByExample(example);
        return itemsImg != null ? itemsImg.getUrl() : "";
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void decreaseItemSpecStock(String itemSpecId, Integer buyCounts){
        int res = itemsMapperCustom.decreaseItemsSpecStock(buyCounts,itemSpecId);
        if(res != 1){
            throw new CustomException(ErrorMsg.STOCK_NOT_ENOUGH);
        }
    }
}
